import json
import time
from email.utils import parsedate_to_datetime
from datetime import datetime
import pytz
import requests

from lxml import etree
import threading
import re

from utils.jingdongEnum import usePaper
from utils.tools import compare_labels, get_file_content


# def format_last_modified(last_modified_str):
#     # 解析Last-Modified字符串为datetime对象
#     dt_gmt = parsedate_to_datetime(last_modified_str)
#
#     # 将GMT时间转换到中国标准时间
#     china_tz = pytz.timezone('Asia/Shanghai')
#     dt_cst = dt_gmt.astimezone(china_tz)
#
#     # 格式化datetime对象为特定格式字符串
#     formatted_date_str = dt_cst.strftime('%a %b %d %Y %H:%M:%S GMT+0800 (中国标准时间)')
#     return formatted_date_str
#
#
# def get_file_content(image_url):
#     res = requests.get(image_url)
#     file_name = image_url.split('/')[-1]
#     last_modified_str = res.headers['last-modified']
#     type = res.headers['content-type']
#     if last_modified_str:
#         last_modified_str = format_last_modified(last_modified_str)
#     else:
#         last_modified_str = 'Fri Jan 26 2024 09:06:16 GMT+0800 (中国标准时间)'
#     size = res.headers['content-length']
#     if size:
#         size = str(size)
#     else:
#         size = '9999'
#     # 检查请求是否成功
#     if res.status_code == 200:
#         return {'content': res.content, 'size': size,
#                 'lastModifiedDate': last_modified_str, 'file_name': file_name, 'type': type}
#     else:
#         return None


# 上传图片
def upload_img1(url, sessionId, index):
    params = {
        'VC_INTEGRATION_JSESSIONID': sessionId,
        'isUpload': 'true',
    }
    result = get_file_content(url)
    files = {
        'id': (None, f'WU_FILE_{index}'),
        'name': (None, result['file_name']),
        'type': (None, result['type']),
        'lastModifiedDate': (None, datetime.now().strftime("%a %b %d %Y %H:%M:%S GMT%z (%Z)")),
        'size': (None, result['size']),
        'file': (result['file_name'], result['content'], result['type']),
    }

    response = requests.post(
        'https://vcbooks.jd.com/sub_books/upload/image2',
        params=params,
        files=files,
    )
    response_json = json.loads(response.text)
    print(response_json)
    if response_json.get('success', False):
        return {'code': 200, 'url': response_json['url']}
    else:
        return {'code': 0, 'message': '操作失败', 'reason': response_json}


def upload_img2(url, sessionId, index):
    params = {
        'VC_INTEGRATION_JSESSIONID': sessionId,
        'isUpload': 'true',
    }
    result = get_file_content(url)
    files = {
        'id': (None, f'WU_FILE_{index}'),
        'name': (None, result['file_name']),
        'type': (None, result['type']),
        'lastModifiedDate': (None, datetime.now().strftime("%a %b %d %Y %H:%M:%S GMT%z (%Z)")),
        'size': (None, result['size']),
        'file': (result['file_name'], result['content'], result['type']),
    }

    response = requests.post(
        'https://vcbooks.jd.com/sub_books/upload/transparentImage2',
        params=params,
        files=files,
    )
    response_json = json.loads(response.text)
    print(response_json)
    if response_json.get('success', False):
        return {'code': 200, 'url': response_json['url']}
    else:
        return {'code': 0, 'message': '操作失败', 'reason': response_json}


# 根据xpath和input的name属性获取input的值
def getValueXpathByName(et, name):
    return et.xpath(f'//*[@name="{name}"]')[0].get('value')


def getTextXpathById(et, id):
    return et.xpath(f'//*[@id="{id}"]')[0].text


def get_select_value(et, name):
    selected_option = et.xpath(f'//*[@name="{name}"]/option[@selected="selected"]')
    selected_value = selected_option[0].get('value') if selected_option else ''
    return selected_value


# 第一步、提交基础信息
def submitBase(book_details_json, wareIds, sessionId):
    cookies = {
        'VC_INTEGRATION_JSESSIONID': sessionId,
    }
    params = {
        'wareId': wareIds,
    }
    page_response = requests.get('https://vcbooks.jd.com/sub_books/edit/init', params=params, cookies=cookies,
                                 headers={})
    et = etree.HTML(page_response.text)
    book_details_json = book_details_json['data']
    series = getValueXpathByName(et, 'series') or book_details_json['seriesTitleName'] or ''
    product_name = et.xpath('//tr/th[text()="商品名称："]/following-sibling::td/input/@value')[0]
    batchNo = getValueXpathByName(et, 'batchNo') or book_details_json['versionNo'] or '1'
    foreignBookName = getValueXpathByName(et, 'foreignBookName') or book_details_json['originalBookName'] or ''
    printNo = getValueXpathByName(et, 'printNo') or book_details_json['printNo'] or ''
    letters = getValueXpathByName(et, 'letters') or book_details_json['fontNumber'] or ''
    drawingNumber = getValueXpathByName(et, 'drawingNumber')  # DCC没这个字段哦
    papers = get_select_value(et, 'papers') or compare_labels(book_details_json['userPaper'], usePaper) or '胶版纸'  # DCC没这个字段哦 --- 这个是必填的！！！！！
    read = getValueXpathByName(et, 'read')  # DCC没这个字段哦
    advertisement = getValueXpathByName(et, 'advertisement') or book_details_json['bookInfoAdditionObj'][
        'advertisingSlogan'] or ''
    brand = getValueXpathByName(et, 'brand')  # DCC没这个字段哦 好像也不需要有
    brandId = getValueXpathByName(et, 'brandId')  # DCC没这个字段哦 好像也不需要有
    upcCode = getValueXpathByName(et, 'upcCode')  # DCC没这个字段哦
    author = getValueXpathByName(et, 'author') or book_details_json['authorName'] or ''
    editor = getValueXpathByName(et, 'editor') or ''  # book_details_json['bookInfoAppendObj']['compiler'] DCC没这个字段
    publishers = getValueXpathByName(et, 'publishers') or book_details_json['publishName'] or ''  # 这个是必填的！！！！！
    proofreader = getValueXpathByName(et, 'proofreader') or book_details_json['bookInfoAppendObj'][
        'proofreadAnnotate'] or ''  # DCC把校对和注释放在一个字段里了
    remarker = getValueXpathByName(et, 'remarker') or book_details_json['bookInfoAppendObj'][
        'proofreadAnnotate'] or ''  # DCC把校对和注释放在一个字段里了
    publishTime = getValueXpathByName(et, 'publishTime') or book_details_json['publishDate'] or ''  # 这个是必填的！！！！！
    transfer = getValueXpathByName(et, 'transfer') or book_details_json['translatorName'] or ''
    drawer = getValueXpathByName(et, 'drawer')  # DCC没这个字段
    printTime = getValueXpathByName(et, 'printTime') or book_details_json['bookInfoAppendObj']['printData'] or ''
    language = getValueXpathByName(et, 'language') or book_details_json['textLanguage'] or ''
    format = getValueXpathByName(et, 'format') or book_details_json['bookSize'] or ''
    pages = getValueXpathByName(et, 'pages') or book_details_json['pagesNumber'] or ''
    keyWord = getValueXpathByName(et, 'keyWord') or ''  # DCC好像没有这个自段，有一个汉语表主题词
    chinaCatalog = getValueXpathByName(et, 'chinaCatalog') or book_details_json['bookInfoAppendObj'][
        'classificationNumber'] or ''
    packages = get_select_value(et, 'packages') or ''  # 这个是必填的！！！！！
    attachment = getValueXpathByName(et, 'attachment') or ''  # DCC没这个字段哦 好像也不需要有
    attachmentNum = getValueXpathByName(et, 'attachmentNum') or ''  # DCC没这个字段哦 好像也不需要有
    packNum = getValueXpathByName(et, 'packNum') or ''  # DCC没这个字段哦 好像也不需要有
    compile = getValueXpathByName(et, 'compile') or ''  # DCC没这个字段
    photography = getValueXpathByName(et, 'photography') or ''  # DCC没这个字段
    dictation = getValueXpathByName(et, 'dictation') or ''  # DCC没这个字段
    finishing = getValueXpathByName(et, 'finishing') or ''  # DCC没这个字段
    write = getValueXpathByName(et, 'write') or ''  # DCC没这个字段
    targetReader = getValueXpathByName(et, 'targetReader') or book_details_json['readerObject'] or ''
    timeStamp = getValueXpathByName(et, 'timeStamp')  # $("input[name=timeStamp]").val()
    applyId = getValueXpathByName(et, 'applyId')
    final_params = {
        'wareId': wareIds,  # 商品编号 必传、不可选、默认值
        'series': series,  # 丛书名
        'wareName': product_name,  # 商品名称
        'batchNo': batchNo,  # 版次 必填
        'foreignBookName': foreignBookName,  # 外文名称
        'printNo': printNo,  # 外文名称
        # isbn不用传
        'letters': letters,  # 字数
        'drawingNumber': drawingNumber,  # 审图号
        'papers': papers,  # 用纸 必填
        # ISSN什么都没有啊
        # 定价也不传
        'read': read,  # 朗读
        'advertisement': advertisement,  # 广告语
        'brand': brand,  # 非注册品牌
        'brandId': brandId,  # 品牌Id 好像和上边的品牌是联动的，先都传空字符串吧
        'upcCode': upcCode,  # 图书附加码
        'author': author,  # 著者
        'editor': editor,  # 编者
        'publishers': publishers,  # 出版社  必填
        'proofreader': proofreader,  # 校对
        'remarker': remarker,  # 注释
        'publishTime': publishTime,  # 出版时间 必填
        'transfer': transfer,  # 译者
        'drawer': drawer,  # 绘者
        'printTime': printTime,  # 印刷时间
        'language': language,  # 正文语种
        'format': format,  # 开本 必填
        'pages': pages,  # 页数
        'keyWord': keyWord,  # 主题词
        'chinaCatalog': chinaCatalog,  # 中图法分类号
        'packages': packages,  # 包装 必填
        'attachment': attachment,  # 附件
        'attachmentNum': attachmentNum,  # 附件数量
        'packNum': packNum,  # 套装数量
        'compile': compile,  # 编纂
        'photography': photography,  # 摄影
        'dictation': dictation,  # 口述
        'finishing': finishing,  # 整理
        'write': write,  # 书写
        'targetReader': targetReader,  # 读者对象
        'isPublishSchedule': 0,  # 使用定时发布功能 0 否， 1 是 ('publishScheduleTime': '',  # 使用定时发布功能后必传 )
        # 主图 imagePathList
        # 'imagePathList[0].skuId': 14095269,  # 商品编号也是skuId
        # 'imagePathList[0].path': 'jfs/t1/234597/32/15617/104412/66125dd8F25fcc9c2/23b145ee45fa1e13.jpg',  # 图片路径
        # 'imagePathList[0].yn': '1',  # 不知道是什么，传的好像都是1
        # 'imagePathList[0].isPrimary': '1',  # 一张图的话默认都是1，带表主图，多张图第一张是1，其他是0
        # 'imagePathList[0].orderSort': '',  # 第一张图的话默认都是''，如果有第二张从1开始，图片顺序
        # # 透明图 最多一张
        # 'transparentImagePathList[0].skuId': 14095269,  # 商品编号也是skuId
        # 'transparentImagePathList[0].path': 'jfs/t1/235222/24/15425/521810/66125de3F7e58b190/a5c4ca3b0e9f1bf7.png',
        # # 图片路径
        # 'transparentImagePathList[0].yn': 1,  # 不知道是什么，传的好像都是1
        # 'transparentImagePathList[0].isPrimary': 2,  # 好像默认是2，
        # 'transparentImagePathList[0].orderSort': '',  # 第一张图的话默认都是''，有且仅有一张图
        'applyId': applyId,
        # applyId在这里！！ document.querySelector('input[name="applyId"]')
        'keywords': '',  # document.querySelector('#keywords'); 页面上并没有显示这个元素
        'isPreviewComposePic': '0',  # document.querySelector('#isPreviewComposePic'); 页面上并没有显示这个元素并且默认值0 hidden
        'summaryFlag': 'true',  # document.querySelector('#summaryFlag'); 页面上并没有显示这个元素并且默认值true hidden
        'timeStamp': timeStamp,  # 不是当前时间戳，这个是他们自己返回的！！
        'videoId': '',  # 视频Id，暂时不传吧
        'editorValue': '',
    }
    # 准备上传图片
    book_info_file_obj_list = book_details_json['bookInfoFileObjList']
    if not book_info_file_obj_list or len(book_info_file_obj_list) == 0:
        return {'code': 0, 'message': '暂无图片信息'}
    zhutu_dcc_urls = []
    for item in book_info_file_obj_list:
        if item["fileType"] == "1":
            zhutu_dcc_urls.append(item)
    if len(zhutu_dcc_urls) == 0:
        return {'code': 0, 'message': '请传入主图'}
    tmsc_dcc_url = next((item for item in book_info_file_obj_list if item["fileType"] == "9"), None)
    if not tmsc_dcc_url:
        return {'code': 0, 'message': '请传入透明素材图'}
    index = 0
    for item in zhutu_dcc_urls:
        data = upload_img1(item['webUrl'], sessionId, index)
        if data['code'] == 0:
            return data
        k1 = f'imagePathList[{index}].skuId'
        k2 = f'imagePathList[{index}].path'
        k3 = f'imagePathList[{index}].yn'
        k4 = f'imagePathList[{index}].isPrimary'
        k5 = f'imagePathList[{index}].orderSort'
        final_params[k1] = wareIds
        final_params[k2] = data['url']
        final_params[k3] = '1'
        final_params[k4] = '0'
        final_params[k5] = str(index)
        if index == 0:
            final_params[k4] = '1'
            final_params[k5] = ''
        index += 1
    tmt_src = upload_img2(tmsc_dcc_url['webUrl'], sessionId, 0)
    if tmt_src['code'] == 0:
        return tmt_src
    final_params['transparentImagePathList[0].skuId'] = 14095269
    final_params['transparentImagePathList[0].path'] = tmt_src['url']
    final_params['transparentImagePathList[0].yn'] = '1'
    final_params['transparentImagePathList[0].isPrimary'] = '2'
    final_params['transparentImagePathList[0].orderSort'] = ''
    response = requests.post('https://vcbooks.jd.com/sub_books/edit/basicInfo', cookies=cookies, headers={},
                             data=final_params)
    # print(response.text)
    final_response = json.loads(response.text)
    # 判断 final_response 里是否包含 state 并且 state 的值是不是等于300
    if final_response.get('state', 0) == 300:
        text_areas = []
        # editorRecommend = getTextXpathById(et, 'editorRecommendEditor')  # 编辑推荐  bookInfoAdditionObj.editRecommend
        # summary = getTextXpathById(et, 'summaryEditor')  # 内容简介  bookInfoAdditionObj.briefIntroduction
        # authorDesc = getTextXpathById(et, 'authorDescEditor')  # 作者简介  bookInfoAdditionObj.authorAbout
        # mediaComment = getTextXpathById(et, 'mediaCommentEditor')  # 精彩书评  DCC没有这个字段
        # directory = getTextXpathById(et, 'directoryEditor')  # 目录  bookInfoAdditionObj.tableOfContents
        # introduction = getTextXpathById(et, 'introductionEditor')  # 精彩书摘  bookInfoAdditionObj.wonderfulClips
        # preface = getTextXpathById(et, 'prefaceEditor')  # 前言/序言  bookInfoAdditionObj.preface
        # illustration = getTextXpathById(et, 'illustrationEditor')  # 内页插图  DCC没有这个字段
        # productFeatures = getTextXpathById(et, 'productFeaturesEditor')  # 产品特色  DCC没有这个字段
        # itemMobileDesc = getTextXpathById(et, 'itemMobileDescEditor')  # 手机端描述  DCC没有这个字段
        element_ids = [
            'editorRecommend',
            'summary',
            'authorDesc',
            # 'mediaComment',
            'directory',
            'introduction',
            'preface',
            # 'illustration',
            # 'productFeatures',
            # 'itemMobileDesc'
        ]
        dcc_obj = {
            'editorRecommend': 'editRecommend',
            'summary': 'briefIntroduction',
            'authorDesc': 'authorAbout',
            'directory': 'tableOfContents',
            'introduction': 'wonderfulClips',
            'preface': 'preface',
        }
        # 遍历每个元素 ID，获取对应元素的文本，并将其添加到 text_areas 列表中
        for element_id in element_ids:
            print(element_id)
            element_text = getTextXpathById(et, element_id + 'Editor')
            if element_text is None and book_details_json['bookInfoAdditionObj'].get(dcc_obj[element_id]):
                text_areas.append(element_id)
        print(text_areas)
        timeStamp = final_response['timeStamp']
        for url_key in text_areas:
            content = book_details_json['bookInfoAdditionObj'].get(dcc_obj[url_key])
            submit_result = submitEditorRecommend(timeStamp, cookies, wareIds, applyId, content, url_key)
            if submit_result['code'] == 0:
                return submit_result
            else:
                timeStamp = submit_result['timeStamp']
        return {'code': 200, 'message': '操作成功！'}
    else:
        return {'code': 0, 'message': '上架基础信息失败！', 'reason': final_response}


# 填编辑推荐
def submitEditorRecommend(timeStamp, cookies, wareIds, applyId, content, url_key):
    data = {
        'applyId': applyId,
        'wareId': wareIds,
        'timeStamp': timeStamp,
        url_key: f'<p>{content}</p>',
    }
    response = requests.post(f'https://vcbooks.jd.com/sub_books/edit/{url_key}', cookies=cookies, data=data)
    response_json = json.loads(response.text)
    if response_json.get('state', 0) == 300:
        return {'code': 200, 'timeStamp': response_json['timeStamp']}
    else:
        return {'code': 0, 'message': '操作失败', 'reason': response_json}


